﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FlickrNet;

namespace FlickrListr
{
	public partial class MainForm : Form
	{
		private string sTempFrob;
		private string sApiKey = "f720046fa15bbbecac5333bc02e5f9ec";
		private string sSharedSecret = "dc18871b7421c180";
		private Flickr flickr;
		private Auth auth;

		public MainForm()
		{
			InitializeComponent();
			flickr = new Flickr(sApiKey, sSharedSecret);
		}

		private void authenticateButton_Click(object sender, EventArgs e)
		{
			sTempFrob = flickr.AuthGetFrob();
			string sAuthenticationUrl = flickr.AuthCalcUrl(sTempFrob, AuthLevel.Write);
			// This doesn't work.  Figure out how we can cached the auth token/frob.
			try {
				auth = flickr.AuthGetToken(sTempFrob);
			}
			catch(FlickrException)
			{
				System.Diagnostics.Process.Start(sAuthenticationUrl);
			}
		}

		private void performButton_Click(object sender, EventArgs e)
		{
			try {
				if (auth == null)
					auth = flickr.AuthGetToken(sTempFrob);
				flickr.AuthToken = auth.Token;
			}
			catch (FlickrException)
			{
				MessageBox.Show("Authentication not yet achieved.  Please authenticate.");
				return;
			}

			outputTextBox.Text = "";
			progressBar.Value = 0;

			PhotoSearchOptions photoSearchOptions = new PhotoSearchOptions(auth.User.UserId);
			DateTime fromDate = fromDatePicker.Value.Date.Add(fromTimePicker.Value.TimeOfDay).ToUniversalTime();
			DateTime toDate = toDatePicker.Value.Date.Add(toTimePicker.Value.TimeOfDay).ToUniversalTime();
			photoSearchOptions.MinUploadDate = fromDate;
			photoSearchOptions.MaxUploadDate = toDate;
			photoSearchOptions.Extras = PhotoSearchExtras.DateTaken | PhotoSearchExtras.DateUploaded;

			PhotoCollection allPhotos = new PhotoCollection();
			Photos photos = flickr.PhotosSearch(photoSearchOptions);

			photoCountLabel.Text = photos.TotalPhotos.ToString("N0");
			progressBar.Maximum = Convert.ToInt32(photos.TotalPhotos);

			while (photos.PageNumber <= photos.TotalPages) {
				foreach (Photo photo in photos.PhotoCollection) {
					StringBuilder stringBuilder = new StringBuilder();
					stringBuilder.Append(photo.Title);
					stringBuilder.Append(", ");
					stringBuilder.Append(photo.DateUploaded.ToLocalTime().ToString());
					stringBuilder.Append(", ");
					stringBuilder.Append(photo.DateTaken.ToLocalTime().ToString());
					stringBuilder.Append(Environment.NewLine);
					outputTextBox.AppendText(stringBuilder.ToString());
					progressBar.Value = progressBar.Value + 1;
				}
				photoSearchOptions.Page = Convert.ToInt32(photos.PageNumber + 1);
				photos = flickr.PhotosSearch(photoSearchOptions);
			}
		}
	}
}
